<?php

namespace App\Jobs;

use AlibabaCloud\Cdn\Cdn;
use AlibabaCloud\Dcdn\Dcdn;
use App\Enums\DnsType;
use App\Enums\DomainType;
use App\Facades\AliyunCdn;
use App\Facades\AliyunDcdn;
use App\Facades\AliyunDns;
use App\Models\DomainPool;

class CreateAliyunDns extends BaseJob
{
    public function __construct(protected DomainPool $pool)
    {
    }

    public function handle(): void
    {
        $this->pool->objectStorageService->aliyun->initClient();
        $host = str_replace('*', '', $this->pool->domain);

        if ($this->pool->type == DomainType::STORAGE) {
            $res = Cdn::v20180510()
                ->describeCdnDomainDetail()
                ->withDomainName($host)
                ->request();
            $value = $res->get('GetDomainDetailModel.Cname');
            AliyunCdn::aliyun($this->pool->objectStorageService->aliyun)
                ->perform($this->pool->domain);
        } else {
            $res = Dcdn::v20180115()
                ->describeDcdnDomainDetail()
                ->withDomainName($host)
                ->request();

            $value = $res->get('DomainDetail.Cname');
            AliyunDcdn::aliyun($this->pool->objectStorageService->aliyun)
                ->perform($this->pool->domain);
        }

        AliyunDns::aliyun($this->pool->aliyun)
            ->store($this->pool->root, $this->pool->rr, $value, DnsType::CNAME);
    }
}
